package com.clusterswisdom.horn.api.quartz;

import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.db.DbUtil;
import com.clusterswisdom.horn.api.event.BaseProcessor;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.ioc.api.RequestParam;

public class ScheduleJob extends BaseProcessor implements Job {
	
	public static final String PARAM_CONFIG = "config";

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			ApiConfig config = (ApiConfig)context.getJobDetail().getJobDataMap().get(PARAM_CONFIG);
			if (config == null) {
				return;
			}
			
			JSONObject param = getParam(config);
			Long logId = null;
			if (config.isLog()) {
				logId = saveCornLog(config, param);
			}
			
			HornResponse response = config.getAction().execute(config, getParam(config));
			Object responseData = super.processResponse(config.getResponse(), response);
			
			if (logId != null) {
				String responseDataValue = responseData == null ? null : responseData.toString();
				DbUtil.getUtil().logResult(logId, config.getResponse().getType().getValue(), responseDataValue);
			}
			
			DbUtil.getUtil().commit();
			
		} catch (Exception e) {
			e.printStackTrace();
		
		} finally {
			DbUtil.getUtil().close();
			
		}
	}

	
	private JSONObject getParam(ApiConfig config) {
		JSONObject param = new JSONObject();
		if (config.getRequest() != null) {
			List<RequestParam> params = config.getRequest().getParams();
			if (params != null && params.size() == 0) {
				for (RequestParam requestParam : params) {
					if (requestParam.getDefaultValue() != null) {
						param.put(requestParam.getName(), requestParam.getDefaultValue());
					}
				}
			}
		}
		
		return param;
	}
	
	private Long saveCornLog(ApiConfig config, JSONObject param) {
		String paramValue = JSON.toJSONString(param);
		String url = config.getService().getService() + "." + config.getName();
		return DbUtil.getUtil().saveLog(config.getService().getChannel(), "cron", url, paramValue);
	}
}
